
package org.smile.json;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.HashMap;

import org.smile.exception.JSONParseException;
import org.smile.json.parser.JSONTokener;
/**
 * JSONObject
 * @author huzhenshan hzs0502030128@163.com
 */
@SuppressWarnings({ "unchecked", "serial" })
public class JSONObject extends HashMap implements JSONAware{
	
	public String toJSONString(){
		return toJSONString(this);
	}
	public JSONObject(Reader reader) throws JSONParseException {
		this(new JSONTokener(reader));
	}
	public JSONObject(String jsonStr) throws JSONParseException {
		this(new JSONTokener(jsonStr));
	}
	public JSONObject(JSONTokener x) throws JSONParseException {
        char c;
        String key;

        if (x.nextClean() != '{') {
            throw x.syntaxError("A JSONObject text must begin with '{'");
        }
        for (;;) {
            c = x.nextClean();
            switch (c) {
            case 0:
                throw x.syntaxError("A JSONObject text must end with '}'");
            case '}':
                return;
            default:
                x.back();
                key = x.nextValue().toString();
            }


            c = x.nextClean();
            if (c == '=') {
                if (x.next() != '>') {
                    x.back();
                }
            } else if (c != ':') {
                throw x.syntaxError("Expected a ':' after a key");
            }
            this.put(key, x.nextValue());


            switch (x.nextClean()) {
            case ';':
            case ',':
                if (x.nextClean() == '}') {
                    return;
                }
                x.back();
                break;
            case '}':
                return;
            default:
                throw x.syntaxError("Expected a ',' or '}'");
            }
        }
    }
	/**
	 *  转成json字符串
	 * @param value
	 * @return
	 */
	public static String toJSONString(Object value) {
		
		return JSONValue.toJSONString(value);
	}

	/**
	 * 写入到一个writer中
	 * @param writer
	 * @throws IOException
	 */
	public void write(Writer writer) throws IOException{
		JSONValue.write(this,writer);
	}
	/**
	 * 写入到一个writer中
	 * @param writer
	 * @throws IOException
	 */
	public static void write(Object json,Writer writer) throws IOException{
		JSONValue.write(json,writer);
	}
	/**
	 * 重写toString方法
	 */
	public String toString() {
		return toJSONString();
	}
}
